import paramiko
import sys
from pathlib import Path

# 配置参数
hostname = "172.16.31.108"
port = 22
username = "root"
password = "123456"
remote_path = "/remote/path/for/debugging"
local_path = "/local/path/to/debug/files"
gdbserver_port = "3000"  # GDB 服务器端口
executable = "oled"  # 要调试的远程可执行文件

# SSH 连接函数


def ssh_connect(hostname, port, username, password):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname, port, username, password)
    return ssh_client

# 执行 SSH 命令


def ssh_command(ssh_client, command):
    stdin, stdout, stderr = ssh_client.exec_command(command)
    return stdout.read().decode('utf-8'), stderr.read().decode('utf-8')

# 上传文件


def upload_files(ssh_client, local_path, remote_path):
    sftp = ssh_client.open_sftp()
    for file in Path(local_path).glob('*'):
        sftp.put(str(file), str(Path(remote_path) / file.name))
    sftp.close()

# 主功能


def main():
    try:
        ssh_client = ssh_connect(hostname, port, username, password)

        # 杀死 gdbserver 端口上的进程
        ssh_command(ssh_client, f"fuser -k {gdbserver_port}/tcp")

        # 上传调试文件
        # upload_files(ssh_client, local_path, remote_path)

        # 改变文件权限
        # ssh_command(ssh_client, f"chmod +x {remote_path}/{executable}")

        # 启动 gdbserver
        ssh_command(
            ssh_client, f" gdbserver :{gdbserver_port} ./{executable}")

        print("gdbserver started successfully.")

    except Exception as e:
        print(f"An error occurred: {e}")
    # finally:
    #     if ssh_client:
    #         ssh_client.close()


if __name__ == "__main__":
    main()
